#include <iostream>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>

// read_map filename
int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }

    // 1. 打开目标文件，mmap需要你自己打开文件
    std::string filename = argv[1];
    int fd = ::open(filename.c_str(), O_RDONLY);
    if(fd < 0)
    {
        std::cout << "Failed to open file: " << filename << std::endl;
        return 2; 
    }

    // 2. 获取文件信息
    struct stat st;
    ::fstat(fd, &st);

    // 3. 文件映射
    char* shmaddr = (char*)::mmap(nullptr, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if(shmaddr == MAP_FAILED)
    {
        std::cout << "Failed to mmap file: " << filename << std::endl;
        return 3; 
    }

    // 4. 进行读文件操作
    std::cout << "File content: " << shmaddr << std::endl;

    // 5. 关闭文件映射
    if(::munmap(shmaddr, st.st_size) == -1)
    {
        std::cout << "Failed to munmap file: " << filename << std::endl;
        return 4;
    }

    // 6. 关闭文件
    ::close(fd);

    return 0;
}